package tea.lib{
	import flash.events.KeyboardEvent;
	import flash.display.Stage;

	public class KeyboardInput
	{
		static private var _intance:KeyboardInput;
		private var _direct:Array;
		private var isDown:Array;
		private var IPCode:Object = { UP:87, DOWN:83, LEFT:65, RIGHT:68, A:74, J:75, D:76, S:79 };
		private var _stage:Stage
		
		static public function get intance():KeyboardInput {
			if (!_intance) {
				_intance = new KeyboardInput();
			}
			return _intance;
		}
		
		public function down(id:String):Boolean {
			return isDown[id];
		}
		
		public function get direct():Array {
			return _direct;
		}
		
		public function get directNum():uint {
			return 5 - _direct[1] * 3 + _direct[0];
		}
		
		public function setInput(_obj:Object):void {
			IPCode = _obj;
		}
		
		public function init(__stage:Stage):void {
			isDown = [];
			_direct = [0, 0];
			for (var k:String in IPCode) {
				isDown[k] = false;
			}
			_stage = __stage;
			_stage.addEventListener(KeyboardEvent.KEY_DOWN,kd);
			_stage.addEventListener(KeyboardEvent.KEY_UP,ku);
		}
		
		public function KeyboardInput():void {
			
		}
		
		private function kd(e:KeyboardEvent):void {
			for (var k:String in IPCode) {
				if (e.keyCode == IPCode[k]) {
					isDown[k] = true;
				}
			}
			isDown[e.keyCode] = true;
			if (e.keyCode==IPCode.UP) {
				_direct[1]=-1;
			} else if (e.keyCode==IPCode.DOWN) {
				_direct[1]=1;
			}
			if (e.keyCode==IPCode.LEFT) {
				_direct[0]=-1;
			} else if (e.keyCode==IPCode.RIGHT) {
				_direct[0]=1;
			}
		}
		private function ku(e:KeyboardEvent):void {
			for (var k:String in IPCode) {
				if (e.keyCode == IPCode[k]) {
					isDown[k] = false;
				}
			}
			isDown[e.keyCode] = false;
			if (e.keyCode==IPCode.UP && _direct[1]==-1) {
				_direct[1]=0;
			} else if (e.keyCode==IPCode.DOWN && _direct[1]==1) {
				_direct[1]=0;
			}
			if (e.keyCode==IPCode.LEFT && _direct[0]==-1) {
				_direct[0]=0;
			} else if (e.keyCode==IPCode.RIGHT && _direct[0]==1) {
				_direct[0]=0;
			}
		}
		
	}
	
}